package com.tianqingwl.gsystem.sysuser.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianqingwl.gsystem.common.vo.CommonResultVo;
import com.tianqingwl.gsystem.common.vo.PageResultVo;
import com.tianqingwl.gsystem.common.vo.ResultVo;
import com.tianqingwl.gsystem.sysuser.pojo.SysRole;
import com.tianqingwl.gsystem.sysuser.pojo.SysUser;
import com.tianqingwl.gsystem.sysuser.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/manage/role")
@PreAuthorize("@gs.check('sys_role_manage')")
public class SysRoleController {
    @Autowired
    private SysRoleService sysRoleService;


    @GetMapping("/list")
    @ResponseBody
    public Object list(Long page,Long limit,Long userId,String roleName,Boolean idEq){
        page = page==null?1:page;
        limit = limit==null?10:limit;

        Page<SysRole> rolePage = new Page<>(page,limit);
        sysRoleService.listSysRolePage(rolePage,userId,roleName,idEq);

        return PageResultVo.success(rolePage.getTotal(),rolePage.getPages(),rolePage.getRecords());
    }

    @GetMapping("/remove")
    @ResponseBody
    public Object remove(Long userId,Long roleId){
        if (userId!=null&&roleId!=null){
            if (userId==1&&roleId==1){
                return CommonResultVo.fail("默认角色不可移出");
            }
            sysRoleService.removeUserRole(userId,roleId);
            return CommonResultVo.success();
        }
        return CommonResultVo.fail("参数不足");
    }
    @GetMapping("/role-manage.html")
    public String roleManagePage(){
        return "manage/role/role-manage";
    }
    @GetMapping("/role-edit.html")
    public String roleEditPage(Model model, Long roleId) {
        if (roleId != null) {
            //修改查询
            SysRole sysRole = sysRoleService.getRoleById(roleId);
            if (sysRole == null) {
                return "redirect:404.html";
            }
            model.addAttribute("sysRole", sysRole);
        }
        return "manage/role/role-edit";
    }

    @GetMapping("/role-permission.html")
    public String rolePermissionPage(){
        return "manage/role/role-permission";
    }

    @GetMapping("/role-permission-select.html")
    public String rolePermissionSelectPage(){
        return "manage/role/role-permission-select";
    }

    @PostMapping({"/roleSave"})
    @ResponseBody
    public ResultVo roleSave(SysRole sysRole) {
        if (sysRole==null){
            return CommonResultVo.fail("未传入数据");
        }
        try {
            SysUser sysUser = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (sysRole.getRoleId()!=null){
                if (sysRole.getRoleId()==1&&sysUser.getUserId()!=1){
                    return CommonResultVo.fail("不可修改默认角色");
                }
            }

            SysRole saveResult = sysRoleService.save(sysRole);
            return CommonResultVo.success(saveResult);
        } catch (Exception e) {
            return CommonResultVo.fail(e.toString());
        }
    }
    @GetMapping({"/delete"})
    @ResponseBody
    public ResultVo delete(Long roleId,Long[] roleIds) {
        try {
            if (roleId!=null){
                boolean have = sysRoleService.haveUser(Arrays.asList(roleId));
                if (have){
                    return CommonResultVo.fail("此角色有关联用户不可删除！");
                }
                if (roleId==1){
                    return CommonResultVo.fail("默认角色不可删除");
                }
                sysRoleService.deleteById(roleId);
            }else if(roleIds!=null&&roleIds.length>0){
                List<Long> roleIdList = Arrays.asList(roleIds);
                boolean have = sysRoleService.haveUser(roleIdList);
                if (have){
                    return CommonResultVo.fail("有角色有关联用户，请重新选择！");
                }
                if (roleIdList.contains(1L)){
                    return CommonResultVo.fail("默认角色不可删除");
                }
                sysRoleService.deleteByIds(Arrays.asList(roleIds));
            }else{
                return CommonResultVo.fail("no id");
            }
            return CommonResultVo.success();
        } catch (Exception e) {
            return CommonResultVo.fail(e.getMessage());
        }
    }

    @PostMapping({"/roleAddPermission"})
    @ResponseBody
    public ResultVo roleAddPermission(Long roleId,Long[] permissionIds) {
        if (roleId==null||permissionIds==null||permissionIds.length==0){
            return CommonResultVo.fail("参数不足");
        }
        try {
            sysRoleService.addPermission(roleId,permissionIds);
            return CommonResultVo.success();
        } catch (Exception e) {
            return CommonResultVo.fail(e.getMessage());
        }
    }
}
